<template>
	<view class="wrap area-b">
		<u-navbar :background="{background:'rgba(0,0,0,0)'}" :border-bottom="false" title="个人信息">
			<view slot="right" class="u-m-r-30" @tap="openSheet">
				<u-icon name="more-dot-fill" size="34"></u-icon>
			</view>
		</u-navbar>
		<view class="head" v-if="!!info">
			<u-avatar :src="info.saveAvatar||info.avatarUrl" size="140" mode="square"></u-avatar>
			<text class="u-m-t-20 u-font-34">{{info.remarks||info.userName}}</text>
		</view>
		<view class="body" v-if="!!info">
			<view class="group" v-if="info.buddy">
				<text class="label">备注名</text>
				<view class="content u-line-1">
					<text>{{info.remarks||'请输入备注名'}}</text>
					
				</view>
				<view class="right">
					<text class="iconfont icon-penfill text-gray" @tap="editRemark"></text>
				</view>
			</view>
			<view class="group">
				<text class="label">昵称</text>
				<view class="content">
					{{info.userName||''}}
				</view>
			</view>
			<view class="group">
				<text class="label">用户号</text>
				<view class="content">
					{{info.userNum||''}}
				</view>
			</view>
<view class="group" v-if="info.profiles">
  <text class="label">个性签名</text>
  <view class="content">
    {{ info.profiles }}
  </view>
</view>

<view class="group" v-else>
  <text class="label">个性签名</text>
  <view class="content">
    空空如也
  </view>
</view>
			<view class="u-m-t-40" v-if="extTxt">
				<view class="u-font-24 text-gray">
					附加信息
				</view>
				<view class="bg-gray u-p-20 u-m-t-10 u-font-24 radius">
					{{extTxt}}
				</view>
			</view>
			<!-- <view class="group" @tap="jumpTo(`/pages/moment/user?id=${id}`)">
				<text class="label">朋友圈</text>
				<view class="u-flex-1">
					点击查看
				</view>
				<text class="iconfont icon-arrow-right text-gray"></text>
			</view> -->
			<view class="u-flex-1">
				
			</view>
			<view class="btn-group" v-if="userId!=id">
				<view v-if="info.buddy" @tap="unfriend" class="btn bg-gray">
					删除好友
				</view>
				<view v-if="info.buddy" @tap="toChat" class="btn bg-blue">
					发送消息
				</view>
				<view v-if="!info.buddy" @tap="apply" class="btn bg-blue">
					添加好友
				</view>
			</view>
		</view>
		<u-modal
			v-model="prompt.show"
			:title="prompt.title" 
			:confirm-text="prompt.confirmText"
			showCancelButton
			@cancel="reject"
			@confirm="resolve"
		>
			<view class="u-p-y-20 u-p-x-30">
				<textarea v-model="prompt.content" class="textarea" maxlength="30" :placeholder="prompt.placeholder" />
			</view>
		</u-modal>
		<u-modal
			v-model="ask.show"
			:title="ask.title" 
			:show-title="!!ask.title"
			showCancelButton
			:content="ask.content"
			:confirm-text="ask.confirmText"
			:cancel-text="ask.cancelText"
			@cancel="reject"
			@confirm="resolve"
		>
		</u-modal>
		<u-action-sheet v-model="sheet.show" :list="sheet.options" @click="resolve"></u-action-sheet>
		<real-dialog v-model="realAsk.show"></real-dialog>
		<vip-dialog v-model="vipAsk.show">
			<text v-if="vipAsk.content" slot="label">{{vipAsk.content}}</text>
		</vip-dialog>
	</view>
</template>

<script>
	import {goback,delay,jumpTo,toast, copy} from "@/utils/util.js"
	import {applyFriend,removeFriend,modifyRemarks} from "@/api/addr.js"
	import {getPortalUserInfo} from "@/api/user.js"
	import {mapGetters,mapActions} from 'vuex'
	import { TYPES as complainT } from "@/api/complain.js"
	import vipDialog from "@/components/dialogs/vip/index.vue"
	import realDialog from "@/components/dialogs/realname/index.vue"
	import DC from "@/DC/index.js"
	import { User } from "@/entity/User"
	import chat, { dictateTypes, msgTypes } from "@/IM"
import { ConversationType } from "@/entity/ConversationType"
	const last_apply = 'apply_friend_last'
	export default {
		components:{
			vipDialog,
			realDialog
		},
		data() {
			return {
				id:'',
				info:null,
				extTxt:'',
				prompt:{
					show:false,
					content:'',
					placeholder:'',
					title:'',
					confirmText:''
				},
				ask:{
					show:false,
					content:'',
					confirmText:'',
					cancelText:''
				},
				sheet:{
					show:false,
					options:[]
				},
				bridge:null,
				realAsk:{
					show:false,
				},
				vipAsk:{
					show:false,
					content:'',
				}
			};
		},
		computed:{
			...mapGetters('user',['userId','userInfo','isReal']),
			...mapGetters('chat',['conversations'])
		},
		onLoad({id}) {
			this.id = id
			this.init()
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.on('setExt',(data)=>{
				this.extTxt = data.remark
			})
		},
		methods:{
			jumpTo,
			...mapActions('chat',['removeHistory','removeConversation','setConversation','sendMessage','saveHistory']),
			...mapActions('addr',['removeFriend','updateFriend','loadOneFriend']),
			resolve(e){
				this.bridge&&this.bridge.resolve&&this.bridge.resolve(e)
			},
			reject(e){
				this.bridge&&this.bridge.reject&&this.bridge.reject(e)
			},
			async init(){
				const user = DC.userDB.getUser(this.id)
				user.fetchOrigin().then(()=>{
					const conv = this.conversations.find((item)=>item.id==this.id)
					if(!!conv){
						this.setConversation({
							id:this.id,
							name:user.userName,
							avatar:user.avatarUrl
						})
					}
				}).catch((e)=>{
					toast(e.retDesc);
				})
				this.info = user
			},
			async toChat(){
				const routes = getCurrentPages()
				const index = routes.findIndex(({route,options})=>route.endsWith('pages/room/single')&&options.id==this.id)
				console.log(index)
				if(index==-1){
					this.setConversation({
						id:this.info.userId,
						type:2,
						avatar:this.info.avatarUrl,
						name:this.info.userName,
						remarks:this.info.remarks
					})
					jumpTo(`/pages/room/single?id=${this.info.userId}`)
				}else{
					goback(routes.length-index-1)
				}
			},
			async unfriend(){ 
				await new Promise((resolve,reject)=>{
					
					this.bridge = {
						resolve,
						reject
					}
					this.openAsk('确定要清除该好友,同时删除与他的所有聊天记录?')
				})
				
				await chat.dictate({
					to:this.id,
					msgType:dictateTypes.delFriend,
					content:'删除了好友',
					extras:{}
				})
				await removeFriend(this.id)
				
				this.removeHistory(this.id)
				this.removeConversation(this.id)
				
				this.removeFriend(this.id)
				goback()
			},
			async apply(){ 
				await new Promise((resolve,reject)=>{
					this.bridge={
						resolve,
						reject
					}
					this.prompt.title = '添加好友'
					this.prompt.confirmText = '申请'
					this.prompt.placeholder = '申请理由(30字内)'
					this.prompt.show = true
					this.prompt.content = `我是${this.userInfo.userName}`
				})
				const {friendId} = await applyFriend({
					uid:this.id,
					remark:this.prompt.content
				})
				await delay(200)
				if(friendId){
					toast('好友添加成功')
					this.info.buddy = true
					this.loadOneFriend(this.info.userId)
					chat.dictate({
						to:this.info.userId,
						msgType:dictateTypes.addFriend,
						content:'添加好友成功',
						extras:{}
					})
					const msg = chat.createMessage({
						to: this.info.userId,
						content: '我们已经是好友了，现在开始聊天吧',
						msgType: msgTypes.TEXT
					})
					this.setConversation({
						id:this.info.userId,
						avatar:this.info.avatarUrl,
						name:this.info.userName,
						type:ConversationType.Single,
						lastMessage:msg
					})
					msg.readBody = {readCount:0,unreadCount:1}
					msg.status = 'loading';
					try {
						await this.sendMessage({
							message: msg,
							id:this.info.userId
						})
						await chat.send(msg)
						msg.status = 'success';
						this.saveHistory()
					} catch (e) {
						console.log(e)
						msg.status = 'error';
					}
				}else{
					toast('好友申请成功')
				}
			},
			async editRemark(){
				await new Promise((resolve,reject)=>{
					this.bridge={
						resolve,
						reject
					}
					this.prompt.title = '修改备注名'
					this.prompt.confirmText = '保存'
					this.prompt.show = true
					this.prompt.content = this.info.remarks
					this.prompt.placeholder = '备注名(30字内)'
				})
				const remarks = this.prompt.content
				await modifyRemarks({
					id:this.info.userId,
					remarks
				})
				this.info.remarks = remarks
				this.updateFriend({
					userId:this.info.userId,
					remarks
				})
				if(this.conversations.some(item=>item.id==this.info.userId)){
					this.setConversation({
						id:this.info.userId,
						type:2,
						remarks
					})
				}
			},
			async complain(){ 
				jumpTo(`/pages/complain/index?btype=${complainT.user}&bid=${this.id}`)
			},
			openAsk(content,title,confirmText='确认',cancelText='取消'){
				this.ask.title = title
				this.ask.content = content
				this.ask.confirmText = confirmText
				this.ask.cancelText = cancelText
				this.ask.show = true
			},
			async openSheet(){
				const index = await new Promise((resolve,reject)=>{
					this.bridge = {
						resolve,
						reject
					}
					this.sheet.show = true
					this.sheet.options = [{text:'举报',fun:'complain'}]
				})
				const opt = this.sheet.options[index]
				this[opt.fun]()
			},
			realGuard(){
				if(!this.isReal){
					this.realAsk.show = true
					throw new Error('请完成实名认证')
				}
			},
			async vipGuard(content){
				if(!this.userInfo.vip){
					
					this.vipAsk.show = true
					this.vipAsk.content = content
					throw new Error('请开通VIP') 
				}
			},
		}
	}
</script>
<style>
	page{
		background-color: #F5F5F5;
	}
</style>
<style lang="scss" scoped>
	.wrap{
		display: flex;
		flex-direction: column;
		min-height: 100vh;
	}
	.head{
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 40rpx;
	}
	.body{
		flex: 1;
		background-color: #FFFFFF;
		border-top-left-radius: 750rpx 100rpx;
		border-top-right-radius: 750rpx 100rpx;
		margin-top: 50rpx;
		padding: 80rpx 30rpx;
		display: flex;
		flex-direction: column;
	}
	.group{
		display: flex;
		align-items: center;
		min-height: 80rpx;
		font-size: 30rpx;
		.label{
			flex: 0 0 150rpx;
			color: #666666;
		}
		.right{
			flexflex-shrink: 0;
			margin-left: 20rpx
		}
	}
	.btn-group{
		display: flex;
		align-items: center;
		justify-content: space-around;
		.btn{
			height: 90rpx;
			width: 300rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 32rpx;
			border-radius: 100rpx;
			&:only-child{
				width: 450rpx;
			}
		}
	}
	.textarea{
		width: 100%;
		height: 160rpx;
		background-color: #F5F5F5;
		padding: 20rpx;
		border-radius: 10rpx;
		font-size: 28rpx;
	}
</style>
